﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Security.Cryptography;
using System.IO;

namespace NWN.GDY.Service.Common
{
    public static class SDString
    {


        /// <summary> 空字符串
        /// </summary>
        public const string EMPTY = "";

        #region Extend Method
        /// <summary>
        /// 是否是有效的Email
        /// </summary>
        /// <param name="emailAddr"></param>
        /// <returns></returns>
        public static bool IsValidEmail(this string emailAddr)
        {
            if (string.IsNullOrEmpty(emailAddr))
                return false;
            return Regex.IsMatch(emailAddr, @"^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$");
        }

        public static bool IsTrimNullOrEmpty(this string str)
        {
            if (string.IsNullOrEmpty(str))
                return true;
            return str.Trim().Length == 0;
        }

        /// <summary>
        /// 是否是有效的身份证
        /// </summary>
        /// <param name="idCard"></param>
        /// <returns></returns>
        public static bool IsValidIdCard(this string idCard)
        {
            if (string.IsNullOrEmpty(idCard))
                return false;

            const string strRegex = @"^\d{15}|\d{17}[\dx]$";
            Regex re = new Regex(strRegex);
            if (re.IsMatch(idCard))
                return true;
            return false;
        }

        /// <summary>
        /// 截取固定长度的字符串，超过部分用省略号代替
        /// </summary>
        /// <param name="str"></param>
        /// <param name="maxWidth"></param>
        /// <returns></returns>
        public static string SubString(this string str, int maxWidth)
        {
            if (IsTrimNullOrEmpty(str)) return string.Empty;

            return abbreviate(str, 0, maxWidth);
        }

        /// <summary>
        /// 数据流转换为十六进制字符串
        /// </summary>
        /// <param name="bytes"></param>
        /// <returns></returns>
        public static string ToHexString(this byte[] bytes)
        {

            if (bytes == null || bytes.Length == 0)
                throw new ArgumentException("bytes [] 参数出错");

            StringBuilder hexString = new StringBuilder(2 * bytes.Length);

            for (int i = 0; i < bytes.Length; i++)
                hexString.AppendFormat("{0:X2}", bytes[i]);

            return hexString.ToString();

        }


        /// <summary>
        /// 获取默认编码的字符串
        /// </summary>
        /// <param name="bytes"></param>
        /// <returns></returns>
        public static string ToDefaultString(this byte[] bytes)
        {
            return Encoding.Default.GetString(bytes);
        }

        public static string ToEncodingString(this byte[] bytes, Encoding encoding)
        {

            return encoding.GetString(bytes);
        }

        /// <summary>
        /// 普通字符串转为十六进制字符串编码
        /// </summary>
        /// <param name="str">普通字符串</param>
        /// <returns>十六进制字符串编码</returns>
        public static string ToHexString(this string str)
        {
            if (string.IsNullOrEmpty(str)) return string.Empty;

            byte[] bytes = Encoding.Default.GetBytes(str);

            return bytes.ToHexString();

        }

        /// <summary>
        /// 普通字符串（指定编码方式）转为十六进制字符串编码
        /// </summary>
        /// <param name="str">指定编码方式的普通字符串</param>
        /// <param name="encoding"></param>
        /// <returns>十六进制字符串</returns>
        public static string ToHexString(this string str, Encoding encoding)
        {
            if (string.IsNullOrEmpty(str)) return string.Empty;
            if (encoding == null)
                return str.ToHexString();

            byte[] bytes = encoding.GetBytes(str);


            return bytes.ToHexString();

        }

        /// <summary>
        /// 十六进制字符串转换为数据流
        /// </summary>
        /// <param name="strHexString">十六进制字符串转换</param>
        /// <returns>字节流</returns>
        public static byte[] ToIntegerBytes(this string strHexString)
        {
            if (string.IsNullOrEmpty(strHexString)) return null;

            int len = strHexString.Length;


            if ((len % 2) != 0)
                throw new Exception("HexString 字符出错!!");

            int byteLen = len / 2;

            byte[] bytes = new byte[byteLen];

            for (int i = 0; i < byteLen; i++)
            {
                bytes[i] = Convert.ToByte(strHexString.Substring(i * 2, 2), 16);
            }

            return bytes;
        }

        /// <summary>
        /// 十六进制字符串转换为指定编码的字符串
        /// </summary>
        /// <param name="strHexString">十六进制字符串</param>
        /// <param name="encoding">编码方式</param>
        /// <returns>还原后的字符串</returns>
        public static string ToIntString(this string strHexString, Encoding encoding)
        {
            byte[] bytes = strHexString.ToIntegerBytes();
            if (bytes == null) return string.Empty;

            encoding = encoding ?? Encoding.Default;

            return encoding.GetString(bytes);

        }

        /// <summary>
        /// 十六进制字符串转换为默认编码的字符串
        /// </summary>
        /// <param name="strHexString"></param>
        /// <returns></returns>
        public static string ToIntString(this string strHexString)
        {
            return strHexString.ToIntString(Encoding.Default);

        }

        /// <summary>
        /// 获取指定编码字符串的MD5摘要信息Mac
        /// </summary>
        /// <param name="text">字符串</param>
        /// <param name="encoding">字符串编码</param>
        /// <returns>十六进制编码的Mac摘要</returns>
        public static string ToMD5Mac(this string text, Encoding encoding)
        {

            var md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
            return md5.ComputeHash(encoding.GetBytes(text)).ToHexString();
        }

        /// <summary>
        /// 获取默认编码字符串的MD5摘要信息Mac
        /// </summary>
        /// <param name="text">原始字符串</param>
        /// <returns>十六进制编码的Mac摘要</returns>
        public static string ToMD5Mac(this string text)
        {
            return text.ToMD5Mac(Encoding.Default);
        }

        /// <summary>
        /// split字符串，采用C#内置的API实现
        /// </summary>
        /// <param name="strOri"></param>
        /// <param name="split"></param>
        /// <returns></returns>
        public static string[] GetSplitArrayNative(this string strOri, string split)
        {
            if (strOri == null || split == null) return null;

            char[] splitArray = split.ToCharArray();
            return strOri.Split(splitArray, StringSplitOptions.RemoveEmptyEntries);
        }

        /// <summary>
        /// split字符串，采用字符","分析
        /// </summary>
        /// <param name="strOri"></param>
        /// <returns></returns>
        public static string[] GetSplitArray(this string strOri)
        {
            return GetSplitArray(strOri, ",");
        }

        /// <summary>
        /// split字符串，采用字符分析
        /// </summary>
        /// <param name="strOri"></param>
        /// <param name="split"></param>
        /// <returns></returns>
        public static string[] GetSplitArray(this string strOri, String split)
        {
            if (strOri == null || split == null) return null;


            return strOri.Split(split.ToCharArray(), StringSplitOptions.RemoveEmptyEntries);

            int offset = 0;
            int index = 0;
            int[] offsets = new int[strOri.Length + 1];

            while (index < strOri.Length)
            {
                int indexOf = strOri.IndexOf(split, index);
                if (indexOf != -1)
                {
                    offsets[offset++] = indexOf;
                    index = (indexOf + split.Length);
                }
                else
                {
                    index = strOri.Length;
                }
            }

            string[] final = new string[offset + 1];
            if (offset == 0)
            {
                final[0] = strOri;
            }
            else
            {
                offset--;
                final[0] = strOri.Substring(0, offsets[0]);
                for (int i = 0; i < offset; i++)
                {
                    final[i + 1] = strOri.Substring(offsets[i] + split.Length, offsets[i + 1] - offsets[i] - split.Length);
                }
                final[offset + 1] = strOri.Substring(offsets[offset] + split.Length);
            }
            return final;
        }

        /// <summary>
        /// 获取字符串左边固定长度的字符串
        /// </summary>
        /// <param name="strOri"></param>
        /// <param name="len">要截取的长度，大于字符串长度则返回源字符串</param>
        /// <returns></returns>
        public static String Left(this string strOri, int len)
        {
            if (string.IsNullOrEmpty(strOri))
                return string.Empty;

            if (len >= strOri.Length) return strOri;
            if (len < 0) return string.Empty;

            return strOri.Substring(0, len);
        }

        /// <summary>
        /// 从右侧截取一定长度的字符串
        /// </summary>
        /// <param name="strOri"></param>
        /// <param name="len">要截取得字符串长度，长度超过源字符串长度，则返回源字符串</param>
        /// <returns></returns>
        public static String Right(this string strOri, int len)
        {
            String strRet;

            if (string.IsNullOrEmpty(strOri))
                return string.Empty;

            if (len <= 0)
            {
                return string.Empty;
            }

            strRet = len >= strOri.Length ? strOri : strOri.Substring(strOri.Length - len, len);

            return strRet;
        }

        /// <summary>
        /// 正则匹配
        /// </summary>
        /// <param name="strInput"></param>
        /// <param name="regPattern"></param>
        /// <returns></returns>
        public static bool IsMatch(this string strInput, string regPattern)
        {
            if (string.IsNullOrEmpty(regPattern))
                throw new ArgumentException("匹配参数能为空");



            return Regex.IsMatch(strInput, regPattern, RegexOptions.IgnoreCase | RegexOptions.Multiline | RegexOptions.Compiled);
        }

        /// <summary>
        /// 正则替换
        /// </summary>
        /// <param name="strInput"></param>
        /// <param name="pattern"></param>
        /// <param name="repalcement"></param>
        /// <returns></returns>
        public static string ReplaceRegex(this string strInput, string pattern, string repalcement)
        {

            if (string.IsNullOrEmpty(strInput))
                return string.Empty;

            if (string.IsNullOrEmpty(pattern))
                throw new ArgumentException("匹配参数能为空");

            if (string.IsNullOrEmpty(repalcement))
                throw new ArgumentException("替换参数不能为空");

            return Regex.Replace(strInput, pattern, repalcement, RegexOptions.IgnoreCase | RegexOptions.Multiline | RegexOptions.Compiled);
        }

        public static string Filter(this string sInput)
        {
            if (sInput.IsNullOrEmpty())
                return sInput;

            return SqlFilter(sInput, true);
        }

        public static bool IsNullOrEmpty(this string str)
        {
            return string.IsNullOrEmpty(str);
        }

        public static T ToType<T>(this string str, T defaultValue)
        {
            return GetValue<T>(str, defaultValue);
        }

        public static int ToInt32(this string str)
        {
            if (str.IsTrimNullOrEmpty())
                throw new ArgumentException("不能转换为整数");

            int i = 0;
            if (int.TryParse(str, out i))
                return i;
            else
                throw new ArgumentException("不能转换为整数");

        }

        public static bool IsInt(this string str)
        {
            int i = 0;
            return int.TryParse(str, out i);
        }

        #endregion

        #region Match of String

        /// <summary> Counts how many times the substring appears in the larger String.
        /// A null or empty ("") String input returns 0.
        /// StringUtils.countMatches(null, *)       = 0
        /// StringUtils.countMatches("", *)         = 0
        /// StringUtils.countMatches("abba", null)  = 0
        /// StringUtils.countMatches("abba", "")    = 0
        /// StringUtils.countMatches("abba", "a")   = 2
        /// StringUtils.countMatches("abba", "ab")  = 1
        /// StringUtils.countMatches("abba", "xxx") = 0
        /// </summary>
        /// <param name="str"> the String to check, may be null
        /// </param>
        /// <param name="sub"> the substring to count, may be null
        /// </param>
        /// <returns> the number of occurrences, 0 if either String is null
        /// </returns>
        public static int countMatches(String str, String sub)
        {
            if (string.IsNullOrEmpty(str))
                return 0;

            int count = 0;
            int idx = 0;
            //'System.String.IndexOf'，可能引发异常。. '
            while ((idx = str.IndexOf(sub, idx)) != -1)
            {
                count++;
                idx += sub.Length;
            }
            return count;
        }
        #endregion


        #region Character Tests

        /// <summary>
        /// Checks if the String contains only ascii code.
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static bool isAscii(System.String str)
        {
            if (str == null)
            {
                return true;
            }
            int sz = str.Length;
            for (int i = 0; i < sz; i++)
            {
                if (!((int)str[i] >= 0 && (int)str[i] <= 255))
                    return false;
            }
            return true;
        }

        /// <summary> Checks if the String contains only unicode letters.
        /// *
        /// null will return false.
        /// An empty String ("") will return true.
        /// *
        /// <pre>
        /// StringUtils.isAlpha(null)   = false
        /// StringUtils.isAlpha("")     = true
        /// StringUtils.isAlpha("  ")   = false
        /// StringUtils.isAlpha("abc")  = true
        /// StringUtils.isAlpha("ab2c") = false
        /// StringUtils.isAlpha("ab-c") = false
        /// </pre>
        /// *
        /// </summary>
        /// <param name="str"> the String to check, may be null
        /// </param>
        /// <returns> true if only contains letters, and is non-null
        /// 
        /// </returns>
        public static bool isAlpha(System.String str)
        {
            if (str == null)
            {
                return false;
            }
            int sz = str.Length;
            for (int i = 0; i < sz; i++)
            {
                if (System.Char.IsLetter(str[i]) == false)
                {
                    return false;
                }
            }
            return true;
        }

        /// <summary> Checks if the String contains only unicode letters and
        /// space (' ').
        /// *
        /// null will return false
        /// An empty String ("") will return true.
        /// *
        /// <pre>
        /// StringUtils.isAlphaSpace(null)   = false
        /// StringUtils.isAlphaSpace("")     = true
        /// StringUtils.isAlphaSpace("  ")   = true
        /// StringUtils.isAlphaSpace("abc")  = true
        /// StringUtils.isAlphaSpace("ab c") = true
        /// StringUtils.isAlphaSpace("ab2c") = false
        /// StringUtils.isAlphaSpace("ab-c") = false
        /// </pre>
        /// *
        /// </summary>
        /// <param name="str"> the String to check, may be null
        /// </param>
        /// <returns> true if only contains letters and space,
        /// and is non-null
        /// 
        /// </returns>
        public static bool isAlphaSpace(System.String str)
        {
            if (str == null)
            {
                return false;
            }
            int sz = str.Length;
            for (int i = 0; i < sz; i++)
            {
                if ((System.Char.IsLetter(str[i]) == false) && (str[i] != ' '))
                {
                    return false;
                }
            }
            return true;
        }

        /// <summary> Checks if the String contains only unicode letters or digits.
        /// *
        /// null will return false.
        /// An empty String ("") will return true.
        /// *
        /// <pre>
        /// StringUtils.isAlphanumeric(null)   = false
        /// StringUtils.isAlphanumeric("")     = true
        /// StringUtils.isAlphanumeric("  ")   = false
        /// StringUtils.isAlphanumeric("abc")  = true
        /// StringUtils.isAlphanumeric("ab c") = false
        /// StringUtils.isAlphanumeric("ab2c") = true
        /// StringUtils.isAlphanumeric("ab-c") = false
        /// </pre>
        /// *
        /// </summary>
        /// <param name="str"> the String to check, may be null
        /// </param>
        /// <returns> true if only contains letters or digits,
        /// and is non-null
        /// 
        /// </returns>
        public static bool isAlphanumeric(System.String str)
        {
            if (str == null)
            {
                return false;
            }
            int sz = str.Length;
            for (int i = 0; i < sz; i++)
            {
                if (System.Char.IsLetterOrDigit(str[i]) == false)
                {
                    return false;
                }
            }
            return true;
        }

        /// <summary> Checks if the String contains only unicode letters, digits
        /// or space (' ').
        /// *
        /// null will return false.
        /// An empty String ("") will return true.
        /// *
        /// <pre>
        /// StringUtils.isAlphanumeric(null)   = false
        /// StringUtils.isAlphanumeric("")     = true
        /// StringUtils.isAlphanumeric("  ")   = true
        /// StringUtils.isAlphanumeric("abc")  = true
        /// StringUtils.isAlphanumeric("ab c") = true
        /// StringUtils.isAlphanumeric("ab2c") = true
        /// StringUtils.isAlphanumeric("ab-c") = false
        /// </pre>
        /// *
        /// </summary>
        /// <param name="str"> the String to check, may be null
        /// </param>
        /// <returns> true if only contains letters, digits or space,
        /// and is non-null
        /// 
        /// </returns>
        public static bool isAlphanumericSpace(System.String str)
        {
            if (str == null)
            {
                return false;
            }
            int sz = str.Length;
            for (int i = 0; i < sz; i++)
            {
                if ((System.Char.IsLetterOrDigit(str[i]) == false) && (str[i] != ' '))
                {
                    return false;
                }
            }
            return true;
        }

        /// <summary> Checks if the String contains only unicode digits.
        /// A decimal point is not a unicode digit and returns false.
        /// *
        /// null will return false.
        /// An empty String ("") will return true.
        /// *
        /// <pre>
        /// StringUtils.isNumeric(null)   = false
        /// StringUtils.isNumeric("")     = true
        /// StringUtils.isNumeric("  ")   = false
        /// StringUtils.isNumeric("123")  = true
        /// StringUtils.isNumeric("12 3") = false
        /// StringUtils.isNumeric("ab2c") = false
        /// StringUtils.isNumeric("12-3") = false
        /// StringUtils.isNumeric("12.3") = false
        /// </pre>
        /// *
        /// </summary>
        /// <param name="str"> the String to check, may be null
        /// </param>
        /// <returns> true if only contains digits, and is non-null
        /// 
        /// </returns>
        public static bool isNumeric(System.String str)
        {
            if (str == null)
            {
                return false;
            }
            int sz = str.Length;
            for (int i = 0; i < sz; i++)
            {
                if (System.Char.IsDigit(str[i]) == false)
                {
                    return false;
                }
            }
            return true;
        }

        /// <summary> Checks if the String contains only unicode digits or space
        /// (' ').
        /// A decimal point is not a unicode digit and returns false.
        /// *
        /// null will return false.
        /// An empty String ("") will return true.
        /// *
        /// <pre>
        /// StringUtils.isNumeric(null)   = false
        /// StringUtils.isNumeric("")     = true
        /// StringUtils.isNumeric("  ")   = true
        /// StringUtils.isNumeric("123")  = true
        /// StringUtils.isNumeric("12 3") = true
        /// StringUtils.isNumeric("ab2c") = false
        /// StringUtils.isNumeric("12-3") = false
        /// StringUtils.isNumeric("12.3") = false
        /// </pre>
        /// *
        /// </summary>
        /// <param name="str"> the String to check, may be null
        /// </param>
        /// <returns> true if only contains digits or space,
        /// and is non-null
        /// 
        /// </returns>
        public static bool isNumericSpace(System.String str)
        {
            if (str == null)
            {
                return false;
            }
            int sz = str.Length;
            for (int i = 0; i < sz; i++)
            {
                if ((System.Char.IsDigit(str[i]) == false) && (str[i] != ' '))
                {
                    return false;
                }
            }
            return true;
        }

        /// <summary> Checks if the String contains only whitespace.
        /// *
        /// null will return false.
        /// An empty String ("") will return true.
        /// *
        /// <pre>
        /// StringUtils.isWhitespace(null)   = false
        /// StringUtils.isWhitespace("")     = true
        /// StringUtils.isWhitespace("  ")   = true
        /// StringUtils.isWhitespace("abc")  = false
        /// StringUtils.isWhitespace("ab2c") = false
        /// StringUtils.isWhitespace("ab-c") = false
        /// </pre>
        /// *
        /// </summary>
        /// <param name="str"> the String to check, may be null
        /// </param>
        /// <returns> true if only contains whitespace, and is non-null
        /// @since 2.0
        /// 
        /// </returns>
        public static bool isWhitespace(System.String str)
        {
            if (str == null)
            {
                return false;
            }
            int sz = str.Length;
            for (int i = 0; i < sz; i++)
            {
                if ((System.Char.IsWhiteSpace(str[i]) == false))
                {
                    return false;
                }
            }
            return true;
        }

        /// <summary>
        /// Checks if the String is an Email
        /// </summary>
        /// <param name="s">the String to check, may be null</param>
        /// <returns></returns>
        public static bool isEmail(string s)
        {
            string strRegex = @"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$";
            Regex re = new Regex(strRegex);
            if (re.IsMatch(s))
                return true;
            else
                return false;
        }
        /// <summary>
        /// Checks if the String is an IdCard
        /// </summary>
        /// <param name="s">the String to check, may be null</param>
        /// <returns></returns>
        public static bool isIdCard(string s)
        {
            string strRegex = @"^\d{15}|\d{17}[\dx]$";
            Regex re = new Regex(strRegex);
            if (re.IsMatch(s))
                return true;
            else
                return false;
        }


        #endregion

        #region Reversing
        /// <summary> Reverses a String as per {@link StringBuffer#reverse()}.
        /// *
        /// null String returns null.
        /// *
        /// <pre>
        /// StringUtils.reverse(null)  = null
        /// StringUtils.reverse("")    = ""
        /// StringUtils.reverse("bat") = "tab"
        /// </pre>
        /// *
        /// </summary>
        /// <param name="str"> the String to reverse, may be null
        /// </param>
        /// <returns> the reversed String, null if null String input
        /// 
        /// </returns>
        public static System.String reverse(this System.String str)
        {
            if (str == null)
            {
                return null;
            }
            char[] tmpChar;
            System.Text.StringBuilder tmpStrBuild;
            tmpChar = new System.Text.StringBuilder(str).ToString().ToCharArray();
            Array.Reverse(tmpChar);
            tmpStrBuild = new System.Text.StringBuilder(new System.String(tmpChar));
            //new System.Text.StringBuilder(str) = tmpStrBuild;
            return tmpStrBuild.ToString();
        }


        #endregion

        #region Abbreviating
        /// <summary> Abbreviates a String using ellipses. This will turn
        /// "Now is the time for all good men" into "Now is the time for..."
        /// *
        /// Specifically:
        /// 
        /// If str is less than maxWidth characters
        /// long, return it.
        /// Else abbreviate it to (substring(str, 0, max-3) + "...").
        /// If maxWidth is less than 4, throw an
        /// IllegalArgumentException.
        /// In no case will it return a String of length greater than
        /// maxWidth.
        /// 
        /// 
        /// *
        /// <pre>
        /// StringUtils.abbreviate(null, *)      = null
        /// StringUtils.abbreviate("", 4)        = ""
        /// StringUtils.abbreviate("abcdefg", 6) = "abc..."
        /// StringUtils.abbreviate("abcdefg", 7) = "abcdefg"
        /// StringUtils.abbreviate("abcdefg", 8) = "abcdefg"
        /// StringUtils.abbreviate("abcdefg", 4) = "a..."
        /// StringUtils.abbreviate("abcdefg", 3) = IllegalArgumentException
        /// </pre>
        /// *
        /// </summary>
        /// <param name="str"> the String to check, may be null
        /// </param>
        /// <param name="maxWidth"> maximum length of result String, must be at least 4
        /// </param>
        /// <returns> abbreviated String, null if null String input
        /// @throws IllegalArgumentException if the width is too small
        /// @since 2.0
        /// 
        /// </returns>
        public static System.String abbreviate(System.String str, int maxWidth)
        {
            return abbreviate(str, 0, maxWidth);
        }

        /// <summary> Abbreviates a String using ellipses. This will turn
        /// "Now is the time for all good men" into "...is the time for..."
        /// *
        /// Works like abbreviate(String, int), but allows you to specify
        /// a "left edge" offset.  Note that this left edge is not necessarily going to
        /// be the leftmost character in the result, or the first character following the
        /// ellipses, but it will appear somewhere in the result.
        /// *
        /// In no case will it return a String of length greater than
        /// maxWidth.
        /// *
        /// <pre>
        /// StringUtils.abbreviate(null, *, *)                = null
        /// StringUtils.abbreviate("", 0, 4)                  = ""
        /// StringUtils.abbreviate("abcdefghijklmno", -1, 10) = "abcdefg..."
        /// StringUtils.abbreviate("abcdefghijklmno", 0, 10)  = "abcdefg..."
        /// StringUtils.abbreviate("abcdefghijklmno", 1, 10)  = "abcdefg..."
        /// StringUtils.abbreviate("abcdefghijklmno", 4, 10)  = "abcdefg..."
        /// StringUtils.abbreviate("abcdefghijklmno", 5, 10)  = "...fghi..."
        /// StringUtils.abbreviate("abcdefghijklmno", 6, 10)  = "...ghij..."
        /// StringUtils.abbreviate("abcdefghijklmno", 8, 10)  = "...ijklmno"
        /// StringUtils.abbreviate("abcdefghijklmno", 10, 10) = "...ijklmno"
        /// StringUtils.abbreviate("abcdefghijklmno", 12, 10) = "...ijklmno"
        /// StringUtils.abbreviate("abcdefghij", 0, 3)        = IllegalArgumentException
        /// StringUtils.abbreviate("abcdefghij", 5, 6)        = IllegalArgumentException
        /// </pre>
        /// *
        /// </summary>
        /// <param name="str"> the String to check, may be null
        /// </param>
        /// <param name="offset"> left edge of source String
        /// </param>
        /// <param name="maxWidth"> maximum length of result String, must be at least 4
        /// </param>
        /// <returns> abbreviated String, null if null String input
        /// @throws IllegalArgumentException if the width is too small
        /// @since 2.0
        /// 
        /// </returns>
        public static System.String abbreviate(System.String str, int offset, int maxWidth)
        {
            if (str == null)
            {
                return null;
            }
            if (maxWidth < 4)
            {
                throw new System.ArgumentException("Minimum abbreviation width is 4");
            }
            if (str.Length <= maxWidth)
            {
                return str;
            }
            if (offset > str.Length)
            {
                offset = str.Length;
            }
            if ((str.Length - offset) < (maxWidth - 3))
            {
                offset = str.Length - (maxWidth - 3);
            }
            if (offset <= 4)
            {
                return str.Substring(0, (maxWidth - 3) - (0)) + "...";
            }
            if (maxWidth < 7)
            {
                throw new System.ArgumentException("Minimum abbreviation width with offset is 7");
            }
            if ((offset + (maxWidth - 3)) < str.Length)
            {
                return "..." + abbreviate(str.Substring(offset), maxWidth - 3);
            }
            return "..." + str.Substring(str.Length - (maxWidth - 3));
        }
        #endregion


        #region 字符串的加密和解密
        //加密
        public static string Encrypt(string key, string iv, string content)
        {
            if ((content == null) || (content.Length == 0))
            {
                throw new Exception("Invalid Argument: Content");
            }
            if ((key == null) || (key.Length != 24))
            {
                throw new Exception("Invalid Argument: Key");
            }
            TripleDES des3 = new TripleDESCryptoServiceProvider();
            byte[] byteKey = Encoding.UTF8.GetBytes(key);
            byte[] byteIv = Encoding.UTF8.GetBytes(iv);
            des3.Mode = CipherMode.CBC;
            des3.Key = byteKey;
            MemoryStream ms;
            CryptoStream cs;
            ICryptoTransform ct = des3.CreateEncryptor(byteKey, byteIv);
            byte[] byt = Encoding.UTF8.GetBytes(content);
            ms = new MemoryStream();
            cs = new CryptoStream(ms, ct, CryptoStreamMode.Write);
            cs.Write(byt, 0, byt.Length);
            cs.FlushFinalBlock();
            cs.Close();
            return Convert.ToBase64String(ms.ToArray());
        }

        //解密
        public static string Decrypt(string key, string iv, string content)
        {
            if ((content == null) || (content.Length == 0))
            {
                throw new Exception("Invalid Argument: Content");
            }
            if ((key == null) || (key.Length != 24))
            {
                throw new Exception("Invalid Argument: Key");
            }
            TripleDES des3 = new TripleDESCryptoServiceProvider();
            byte[] byteKey = Encoding.UTF8.GetBytes(key);
            byte[] byteIv = Encoding.UTF8.GetBytes(iv);
            des3.Mode = CipherMode.CBC;
            des3.Key = byteKey;
            des3.IV = byteIv;
            MemoryStream ms;
            CryptoStream cs;
            ICryptoTransform ct = des3.CreateEncryptor(byteKey, byteIv);
            ct = des3.CreateDecryptor(des3.Key, des3.IV);
            byte[] byt = Convert.FromBase64String(content);
            ms = new MemoryStream();
            cs = new CryptoStream(ms, ct, CryptoStreamMode.Write);
            cs.Write(byt, 0, byt.Length);
            cs.FlushFinalBlock();
            cs.Close();
            return Encoding.UTF8.GetString(ms.ToArray());
        }
        #endregion




        /// <summary>
        /// Checks whether the String a valid Java number.
        /// Valid numbers include hexadecimal marked with the 0x
        /// qualifier, scientific notation and numbers marked with a type
        /// qualifier (e.g. 123L).
        /// 
        /// Null and empty String will return
        /// false.
        /// 
        /// </summary>
        /// <param name="str"> the String to check
        /// </param>
        /// <returns> true if the string is a correctly formatted number
        /// 
        /// </returns>
        public static bool isNumber(System.String str)
        {
            if (string.IsNullOrEmpty(str))
            {
                return false;
            }
            char[] chars = str.ToCharArray();
            int sz = chars.Length;
            bool hasExp = false;
            bool hasDecPoint = false;
            bool allowSigns = false;
            bool foundDigit = false;
            // deal with any possible sign up front
            int start = (chars[0] == '-') ? 1 : 0;
            if (sz > start + 1)
            {
                if (chars[start] == '0' && chars[start + 1] == 'x')
                {
                    int i = start + 2;
                    if (i == sz)
                    {
                        return false; // str == "0x"
                    }
                    // checking hex (it can't be anything else)
                    for (; i < chars.Length; i++)
                    {
                        if ((chars[i] < '0' || chars[i] > '9') && (chars[i] < 'a' || chars[i] > 'f') && (chars[i] < 'A' || chars[i] > 'F'))
                        {
                            return false;
                        }
                    }
                    return true;
                }
            }
            sz--; // don't want to loop to the last char, check it afterwords
            // for type qualifiers
            int i2 = start;
            // loop to the next to last char or to the last char if we need another digit to
            // make a valid number (e.g. chars[0..5] = "1234E")
            while (i2 < sz || (i2 < sz + 1 && allowSigns && !foundDigit))
            {
                if (chars[i2] >= '0' && chars[i2] <= '9')
                {
                    foundDigit = true;
                    allowSigns = false;
                }
                else if (chars[i2] == '.')
                {
                    if (hasDecPoint || hasExp)
                    {
                        // two decimal points or dec in exponent   
                        return false;
                    }
                    hasDecPoint = true;
                }
                else if (chars[i2] == 'e' || chars[i2] == 'E')
                {
                    // we've already taken care of hex.
                    if (hasExp)
                    {
                        // two E's
                        return false;
                    }
                    if (!foundDigit)
                    {
                        return false;
                    }
                    hasExp = true;
                    allowSigns = true;
                }
                else if (chars[i2] == '+' || chars[i2] == '-')
                {
                    if (!allowSigns)
                    {
                        return false;
                    }
                    allowSigns = false;
                    foundDigit = false; // we need a digit after the E
                }
                else
                {
                    return false;
                }
                i2++;
            }
            if (i2 < chars.Length)
            {
                if (chars[i2] >= '0' && chars[i2] <= '9')
                {
                    // no type qualifier, OK
                    return true;
                }
                if (chars[i2] == 'e' || chars[i2] == 'E')
                {
                    // can't have an E at the last byte
                    return false;
                }
                if (!allowSigns && (chars[i2] == 'd' || chars[i2] == 'D' || chars[i2] == 'f' || chars[i2] == 'F'))
                {
                    return foundDigit;
                }
                if (chars[i2] == 'l' || chars[i2] == 'L')
                {
                    // not allowing L with an exponent
                    return foundDigit && !hasExp;
                }
                // last character is illegal
                return false;
            }
            // allowSigns is true iff the val ends in 'E'
            // found digit it to make sure weird stuff like '.' and '1E-' doesn't pass
            return !allowSigns && foundDigit;
        }

        /// <summary>  
        /// 对数据库操作的字符串进行转意处理，主要是针对"'"的
        /// </summary>
        /// <param name="strOri">   
        /// 待转意的字符串
        /// </param>
        /// <return>  转意后的字符串
        /// 例如：
        /// 字符串str = "上海盛大'Shanda'"，在调用convertSQL(str)之后，得到的新串
        /// 是"上海盛大''Shanda''"，是将一个"'"转化为两个"''"。
        /// *
        /// 
        /// </return>
        public static string ConvertSQL(string strOri)
        {
            if (strOri == null)
            {
                return "";
            }


            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            int nLen = strOri.Length;
            for (int i = 0; i < nLen; i++)
            {
                if (strOri[i] == '\'')
                {
                    sb.Append("'");
                    sb.Append(strOri[i]);
                }
                else
                {
                    sb.Append(strOri[i]);
                }
            }


            return sb.ToString();
        }

        #region Sql防注入过滤
        /// <summary>
        /// Sql防注入过滤
        /// </summary>
        /// <param name="str">字符串值</param>
        /// <param name="IsInput">是否为输入转换</param>
        /// <returns>返回转换后的字符串</returns>
        public static string SqlFilter(string str, bool IsInput)
        {
            string Rv = str;
            if (IsInput)
            {//输入转换
                Rv = Rv.Replace(@"'", "&#39;");
                //Rv = Rv.Replace(@":","&#58;");
                Rv = Rv.Replace(@"--", "&#45;&#45;");
                Rv = Rv.Replace(@"%", "&#37;");
                //Rv = Rv.Replace(@"_","&#95;");
                Rv = Rv.Replace(@"<", "&#60;");
                Rv = Rv.Replace(@">", "&#62;");
                Rv = Rv.Replace(@"\", "&#92;");
            }
            else
            {//输出转换
                Rv = Rv.Replace("&#92;", @"\");
                Rv = Rv.Replace("&#39;", @"'");
                Rv = Rv.Replace("&#58;", @":");
                Rv = Rv.Replace("&#45;&#45;", @"--");
                Rv = Rv.Replace("&#37;", @"%");
                Rv = Rv.Replace("&#95;", @"_");
                Rv = Rv.Replace("&#60;", "<");
                Rv = Rv.Replace("&#62;", ">");
                //Rv = Rv.Replace("\r\n","<br>");
                //Rv = Rv.Replace(" ","&nbsp;");
            }
            return Rv;
        }
        #endregion

        /// <summary>  
        /// 对在页面上显示的字符串进行转意处理，主要是针对"<>"的
        /// </summary>
        /// <param name="strOri">待转意的字符串</param>
        ///<return>转意后的字符串
        /// 例如：
        /// 字符串str = "<hello>"，在调用convertHTML(str)之后，得到的新串
        /// 是"&lt;hello&lg;"，是将"<"转化成"&lt;"，还有将">"转化为"&lg;"。
        /// 主要是为了避免在页面上显示出现混乱
        /// </return>
        public static string ConvertHTML(string strOri)
        {

            System.String strRet = null;
            if (strOri == null || strOri.Equals(""))
            {
                strRet = "";
            }
            else
            {
                System.Text.StringBuilder sb = new System.Text.StringBuilder(strOri);
                sb = sb.Replace("&", "&amp;");
                sb = sb.Replace("<", "&lt;");
                sb = sb.Replace(">", "&gt;");
                sb = sb.Replace("\"", "&quot;");
                sb = sb.Replace(" ", "&nbsp;");
                //sb = sb.Replace("\n","");
                //				for (int i = 0; i < sb.Length; i++)
                //				{
                //					/* 新增对\n,空格等字符的转码 */
                //					char current = sb[i];
                //					switch (current)
                //					{
                //						
                //						case '<': 
                //							sb = sb.Remove(i,1);
                //							sb = sb.Insert(i, "&lt;");
                //							i = i + 3;
                //							break;
                //						
                //						case '>': 
                //							sb = sb.Remove(i,1);
                //							sb = sb.Insert(i, "&gt;");
                //							i = i + 3;
                //							break;
                //						
                //						case ' ': 
                //							sb = sb.Remove(i,1);
                //							sb = sb.Insert(i, "&nbsp;");
                //							i = i + 5;
                //							break;
                //						
                //						case '\n': 
                //							sb = sb.Remove(i,1);
                //							sb = sb.Insert(i, "");
                //							i = i + 3;
                //							break;
                //						}
                //				}
                strRet = sb.ToString(); //大家不要使用str=new String(xx)的形式;
            }
            return strRet;
        }

        /// <summary>
        /// 对Input TextBox中输入的字符串进行检查，
        /// 过滤有害的html标签,
        /// 限制字符串的长度，
        /// 过滤对sql有害的"'".
        /// </summary>
        /// <param name="inputString">要过滤得字符串</param>
        /// <param name="maxLength">字符串最大长度</param>
        /// <returns>过滤好的安全的字符串</returns>
        public static string InputText(string inputString, int maxLength)
        {
            StringBuilder retVal = new StringBuilder();

            string convertedString = "";

            // check incoming parameters for null or blank string
            if ((inputString != null) && (inputString != String.Empty))
            {
                inputString = inputString.Trim();

                //chop the string incase the client-side max length
                //fields are bypassed to prevent buffer over-runs
                if (inputString.Length > maxLength)
                    inputString = inputString.Substring(0, maxLength);

                //convert some harmful symbols incase the regular
                //expression validators are changed
                for (int i = 0; i < inputString.Length; i++)
                {
                    switch (inputString[i])
                    {
                        case '"':
                            retVal.Append("&quot;");
                            break;
                        case '<':
                            retVal.Append("&lt;");
                            break;
                        case '>':
                            retVal.Append("&gt;");
                            break;
                        default:
                            retVal.Append(inputString[i]);
                            break;
                    }
                }


                // Replace single quotes with tow quotes
                retVal.Replace("'", "''");
                convertedString = retVal.ToString();
                //chop the string incase the client-side max length
                //fields are bypassed to prevent buffer over-runs
                if (convertedString.Length > maxLength)
                    convertedString = convertedString.Substring(0, maxLength);
            }

            return convertedString.ToString();

        }



        /// <summary>
        /// /// 对Input TextBox中输入的字符串进行检查，
        /// 过滤有害的html标签,
        /// 限制字符串的长度，
        ///
        /// </summary>
        /// <param name="inputString"></param>
        /// <param name="maxLength"></param>
        /// <returns></returns>
        public static string InputText2(string inputString, int maxLength)
        {
            StringBuilder retVal = new StringBuilder();
            string convertedString = "";
            // check incoming parameters for null or blank string
            if ((inputString != null) && (inputString != String.Empty))
            {
                inputString = inputString.Trim();

                //chop the string incase the client-side max length
                //fields are bypassed to prevent buffer over-runs
                if (inputString.Length > maxLength)
                    inputString = inputString.Substring(0, maxLength);

                //convert some harmful symbols incase the regular
                //expression validators are changed
                for (int i = 0; i < inputString.Length; i++)
                {
                    switch (inputString[i])
                    {
                        case '"':
                            retVal.Append("&quot;");
                            break;
                        case '<':
                            retVal.Append("&lt;");
                            break;
                        case '>':
                            retVal.Append("&gt;");
                            break;
                        default:
                            retVal.Append(inputString[i]);
                            break;
                    }
                }


                //chop the string incase the client-side max length
                //fields are bypassed to prevent buffer over-runs
                convertedString = retVal.ToString();
                //chop the string incase the client-side max length
                //fields are bypassed to prevent buffer over-runs
                if (convertedString.Length > maxLength)
                    convertedString = convertedString.Substring(0, maxLength);
            }

            return retVal.ToString();
        }

        /// <summary>  
        /// 获得字符串的长度，该字符串包括中英文的字符串
        /// </summary>
        /// <param name="strOri"> 待求长度的字符串</param>
        /// <return>       
        ///  该字符串的长度
        /// 例如：
        /// 字符串"中国，china."的长度是"12"，
        /// 若输入的字符串为"null"或为空""，则长度为"0"
        /// 注意汉字的标点符号占两个字符长度。
        ///</return>
        public static int GetBytesLength(System.String strOri)
        {

            return GetBytesLength(strOri, Encoding.Default);


        }

        /// <summary>
        /// 按指定Encoding方式取得字符串的字节数
        /// </summary>
        /// <param name="strOri">字符串</param>
        /// <param name="encoding">编码方式</param>
        /// <returns>字节数量</returns>
        public static int GetBytesLength(string strOri, Encoding encoding)
        {
            int nRet = 0;

            if (strOri == null || strOri.Length == 0)
            {
                nRet = 0;
            }
            else
            {

                byte[] b_array = encoding.GetBytes(strOri);
                nRet = b_array.Length;
            }

            return nRet;
        }

        /// <summary>
        /// 按指定Encoding方式把指定字符串转换为字节数组
        /// </summary>
        /// <param name="strOri">要转换字符串</param>
        /// <param name="encoding">编码方式</param>
        /// <returns>字符数组</returns>
        public static byte[] GetBytes(string strOri, Encoding encoding)
        {
            if (strOri == null || strOri.Length == 0)
                return new byte[0];

            return encoding.GetBytes(strOri);

        }


        /// <summary>
        /// 按默认编码方式把指定字符串转换为字节数组
        /// </summary>
        /// <param name="strOri">要转换字符串</param>
        /// <returns>字符数组</returns>
        public static byte[] GetBytes(string strOri)
        {

            return GetBytes(strOri, Encoding.Default);

        }

        /// <summary>
        /// 把指定字符串转换为gb2312编码的字符串
        /// </summary>
        /// <param name="strOri"></param>
        /// <returns></returns>
        public static string GetGB2312String(string strOri)
        {
            if (null == strOri)
                return null;

            byte[] a = Encoding.GetEncoding("gb2312").GetBytes(strOri);
            return Encoding.GetEncoding("gb2312").GetString(a);

        }

        /// <summary>
        /// getHexString方法主要是，把字符串按每一个字母
        /// 转换成ASCII的无符号整形（十六进制）的整数字符串
        /// </summary>
        /// <param name="strValue">要转换的字符串</param>
        /// <return>16进制字符串</return>
        public static System.String GetHexString(System.String strValue)
        {
            if (strValue == null)
                return null;

            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            char c;
            int v;

            for (int i = 0; i < strValue.Length; i++)
            {
                c = strValue[i];
                v = (int)c & 0xffff;
                sb.Append(" 0X").Append(System.Convert.ToString(v, 16));
            }
            return sb.ToString();
        }

        /// <summary>
        /// 十六进制的字符串转传成十进制的数字，只限转换一个数字
        /// 如“AB”、“20”(表示十进制的 32) 等
        /// </summary>
        /// <param name="HexString">十六进制的字符串</param>
        /// <returns>十进制数字</returns>
        public static int HexStringToInt(string HexString)
        {
            return int.Parse(HexString, System.Globalization.NumberStyles.HexNumber);
        }

        /// <summary>
        /// 十进制数字转成十六进制的字符串， 只限一个数字转换
        /// </summary>
        /// <param name="i"></param>
        /// <returns></returns>
        public static string IntToHexString(int i)
        {
            return i.ToString("X4");

        }



        /// <summary>
        /// 数据流转换为十六进制字符串
        /// </summary>
        /// <param name="bytes"></param>
        /// <returns></returns>
        public static string ByteArrayToHexString(byte[] bytes)
        {

            if (bytes == null || bytes.Length == 0)

                throw new ArgumentException("bytes [] 参数出错");

            StringBuilder hexString = new StringBuilder(2 * bytes.Length);

            for (int i = 0; i < bytes.Length; i++)
                hexString.AppendFormat("{0:X2}", bytes[i]);

            return hexString.ToString();

        }

        /// <summary>
        /// 十六进制字符串转换为数据流
        /// </summary>
        /// <param name="strHexString"></param>
        /// <returns></returns>
        public static byte[] HexStringToByteArray(string strHexString)
        {

            int len = strHexString.Length;


            if ((len % 2) != 0)
                throw new Exception("HexString 字符出错!!");

            int byteLen = len / 2;

            byte[] bytes = new byte[byteLen];

            for (int i = 0; i < byteLen; i++)
            {
                bytes[i] = Convert.ToByte(strHexString.Substring(i * 2, 2), 16);
            }

            return bytes;
        }





        /// <summary>  截取字符串的长度，获得该字符串从左边起多少位之后的字符串的长度
        /// </summary>
        /// <param name="strOri"> 待截取长度的字符串
        /// </param>
        /// <param name="nPos">   从左边起所偏移的位数
        /// </param>
        /// <param name="nLength">要截取的字符串的长度
        /// </param>
        /// <return>        被截取的字符串
        /// 例如：
        /// 字符串str = "Shanda of ShangHai"，如果调用该函数mid(str,8,2)之后，
        /// 所返回的字符串为"ShangHai"。
        /// 若输入的字符串为"null"或为""，则返回""。
        /// 若输入的左偏移位数小于等于0，则返回原串。
        /// 若输入的左偏移位数大于等于该字符串的长度，并且截取长度小于等于0，则返回""。
        /// 若输入的左偏移位数大于等于该字符串的长度，并且截取长度大于等于剩下部分的长度，
        /// 则返回剩下部分。
        /// 
        /// </return>
        public static System.String Mid(System.String strOri, int nPos, int nLength)
        {
            string strRet = "";

            if (strOri == null || strOri.Length == 0)
            {
                strRet = "";
            }
            else
            {
                if (nPos < 0)
                {
                    nPos = 0;
                }
                else
                {
                    if (nLength <= 0)
                    {
                        strRet = "";
                    }
                    else
                    {
                        if (nPos >= strOri.Length)
                        {
                            strRet = "";
                        }
                        else
                        {
                            if (nLength >= (strOri.Length - nPos))
                            {
                                strRet = strOri.Substring(nPos);
                            }
                            else
                            {
                                strRet = strOri.Substring(nPos, nLength);
                            }
                        }
                    }
                }
            }

            return strRet;
        }



        /// <summary> 为根据分割符号来拆分字符串
        /// </summary>
        /// <param name="strOri">    目标字符串
        /// </param>
        /// <param name="strSplit">  分割标识符
        /// </param>
        /// <return>           分割后的字符串
        /// 例如：
        /// 字符串str = "d:\\shanda\\esales\\util"，调用split(str,"\\")之后，返回一个
        /// string[]，包括("d:","shanda","esales","util")这四个元素。
        /// 若字符串是"a,b,c,d,e"，则调用split("a,b,c,d,e",",")之后，返回一个
        /// string[]，包括("a","b","c","d","e")这五个元素。
        /// </return>
        public static string[] Split(System.String strOri, System.String split)
        {
            if (strOri == null || split == null) return null;

            int offset = 0;
            int index = 0;
            int[] offsets = new int[strOri.Length + 1];

            while (index < strOri.Length)
            {
                int indexOf = strOri.IndexOf(split, index);
                if (indexOf != -1)
                {
                    offsets[offset++] = indexOf;
                    index = (indexOf + split.Length);
                }
                else
                {
                    index = strOri.Length;
                }
            }

            string[] final = new string[offset + 1];
            if (offset == 0)
            {
                final[0] = strOri;
            }
            else
            {
                offset--;
                final[0] = strOri.Substring(0, offsets[0]);
                for (int i = 0; i < offset; i++)
                {
                    final[i + 1] = strOri.Substring(offsets[i] + split.Length, offsets[i + 1] - offsets[i] - split.Length);
                }
                final[offset + 1] = strOri.Substring(offsets[offset] + split.Length);
            }
            return final;
        }

        #region 类型转换
        public static T GetValue<T>(string input, T defaultValue)
        {
            T rv = defaultValue;
            try
            {
                rv = (T)Convert.ChangeType(input, typeof(T));
            }
            catch { }
            return rv;
        }
        #endregion

        #region 货币转换
        public static string FormatDecimal(decimal dValue)
        {
            //string temp = dValue.ToString();
            //int index = temp.IndexOf(".");
            //if (index == -1) return temp + ".00";
            //else
            //{
            //    string iPart = temp.Substring(0, index);
            //    int len = temp.Length - iPart.Length - 1;
            //    string dPart = temp.Substring(index + 1, len);
            //    if (dPart.Length < 2) dPart = dPart + "0";
            //    if (dPart.Length > 2) dPart = dPart.Substring(0, 2);

            //    return iPart + "." + dPart;
            //}
            return dValue.ToString("F2");
        }

        public static string FormatDecimal(decimal dValue, int min)
        {

            StringBuilder sb = new StringBuilder();
            sb.Append('.');

            for (int i = 0; i < min; i++)
            {
                sb.Append('0');
            }
            return dValue.ToString(sb.ToString());
        }
        #endregion

        #region Ip地址检测(IPv4)
        public static bool IsIpAddress(string input)
        {
            if (string.IsNullOrEmpty(input))
                return false;
            return Regex.IsMatch(input, @"(^((1?\d?\d|(2([0-4]\d|5[0-5])))\.){3}(1?\d?\d|(2([0-4]\d|5[0-5])))$)");
        }
        public static bool IsIp(this string input)
        {
            if (string.IsNullOrEmpty(input))
                return false;
            return Regex.IsMatch(input, @"(^((1?\d?\d|(2([0-4]\d|5[0-5])))\.){3}(1?\d?\d|(2([0-4]\d|5[0-5])))$)");
        }
        #endregion

        #region 解码并编码多行文本
        public static string TextEncode(this string s)
        {
            if (string.IsNullOrEmpty(s))
                return "";
            return System.Web.HttpContext.Current.Server.HtmlEncode(s).Replace(" ", "&nbsp;").Replace("\r\n", "<br />").Replace("\n", "<br />");
        }

        public static string TextDecode(this string s)
        {
            if (string.IsNullOrEmpty(s))
                return "";
            string temp = System.Web.HttpContext.Current.Server.HtmlDecode(s).Replace("&nbsp;", " ").Replace("<br />", "\n");
            Regex regex = new Regex(
                        @"<[^>]+>",
                        RegexOptions.IgnoreCase
                        | RegexOptions.Multiline
                        | RegexOptions.IgnorePatternWhitespace
                        | RegexOptions.Compiled
                        );
            temp = regex.Replace(temp, "");
            return temp;
        }
        #endregion

        public static string JoinArray(this string[] strArray, string seperator)
        {
            if (strArray == null || strArray.Length == 0)
                return "";

            StringBuilder sb = new StringBuilder();
            foreach (string s in strArray)
            {
                sb.Append(s).Append(seperator);
            }
            sb.Remove(sb.Length - seperator.Length, seperator.Length);
            return sb.ToString();
        }
    }
}
